package com.itlaoqi.thread;

import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class SemaphoreSample1 {

    public static void main(String[] args) {
        ExecutorService threadPool = Executors.newCachedThreadPool();
        Semaphore semaphore = new Semaphore(10);//定义5个信号量，也就是说服务器只允许5个人再里面玩
        for (int i = 0; i <= 2000; i++) {
            final int index = 1;
            threadPool.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        semaphore.acquire();//获取一个信号量//占用一个跑道
                        play();
                        semaphore.release();//执行完毕后释放信号量，也就是说服务器只允许5个人在里面玩
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
        threadPool.shutdown();
    }
    public static void play(){
        System.out.println(new Date() + Thread.currentThread().getName() + "获得紫禁之巅服务器进入资格");
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(new Date() + Thread.currentThread().getName() + "紫禁之巅服务器退出");
    }
}
